package com.example.gfsquadwebviewproject.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.example.gfsquadwebviewproject.R;
import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.fragment.IBaseFragmentBack;
import com.example.gfsquadwebviewproject.fragment.setting.SettingFragment;
import com.example.gfsquadwebviewproject.fragment.webview.WebViewFragment;
import com.example.gfsquadwebviewproject.log.WriteFileLog;
import com.example.gfsquadwebviewproject.m_enum.GlobalHodler;
import com.example.gfsquadwebviewproject.m_enum.GlobalObject;
import com.example.gfsquadwebviewproject.net.NetWorkStateReceiver;
import com.example.gfsquadwebviewproject.presenter.service.mqtt.IMqttCallbcak;
import com.example.gfsquadwebviewproject.presenter.service.mqtt.IMqttService;
import com.example.gfsquadwebviewproject.presenter.service.mqtt.MqttServiceClass;
import com.example.gfsquadwebviewproject.presenter.update.UpdateAppClassHolder;
import com.example.gfsquadwebviewproject.util.L;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import static android.view.KeyEvent.ACTION_UP;
import static android.view.KeyEvent.KEYCODE_BACK;

public class MainActivity extends AppCompatActivity implements IBaseFragmentBack , IMqttCallbcak {
    String TAG = "MainActivity_Context";
    Constant constant;
    WriteFileLog writeFileLog;

    FragmentManager fragmentManager;//管理者
    FragmentTransaction fragmentTransaction;//事件处理

    WebViewFragment webViewFragment;//主显示界面 webview
    SettingFragment settingFragment;//设置界面

    HashMap<Integer,Fragment> fragmentHashMap;//现有的Fragment类
    HashMap<Fragment,String> fragment_Tag_HshMap;//fragment对应的TAG

    String WEBVIEW_FRAGMENT_TAG = "webViewFragment";
    String SETTING_FRAGMENT_TAG = "settingFragment";

    NetWorkStateReceiver netWorkStateReceiver;//网络监控
    IActivityTouchEvent iActivityTouchEvent;//屏幕触碰接口
    IMqttService iMqttService;
    GlobalHodler globalHodler;
    UpdateAppClassHolder updateAppClassHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消系统时间状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        //权限
        if (Build.VERSION.SDK_INT >= 23){
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.INTERNET,
                            Manifest.permission.CHANGE_NETWORK_STATE,
                            Manifest.permission.ACCESS_WIFI_STATE,
                            Manifest.permission.ACCESS_NETWORK_STATE,
                            Manifest.permission.REQUEST_INSTALL_PACKAGES
                    },
                    1);
        }

        globalHodler = GlobalHodler.instance();
        globalHodler.setHashMap(GlobalObject.ACTIVITY,(Activity)this);

        updateAppClassHolder = UpdateAppClassHolder.instance(getApplicationContext());

        iMqttService = new MqttServiceClass(getApplicationContext(),this);

        writeFileLog = new WriteFileLog(getApplicationContext());
        writeFileLog.writeLog("MainActivity onCreate");

        //检测网络
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(constant.ACTION_NETWORK_CHANGE);
        registerReceiver(netWorkStateReceiver, filter);

        fragmentManager = getSupportFragmentManager();

        fragmentHashMap = new HashMap<>();
        fragment_Tag_HshMap = new HashMap<>();

        webViewFragment = new WebViewFragment();//主显示界面 webview
        settingFragment = new SettingFragment();//设置界面

        fragment_Tag_HshMap.put(webViewFragment,WEBVIEW_FRAGMENT_TAG);//主显示界面 webview 的 TAG
        fragment_Tag_HshMap.put(settingFragment,SETTING_FRAGMENT_TAG);//设置界面 的 TAG

        addFragment(R.id.activity_fragement,webViewFragment);//默认显示webview界面
        startMqttService();

//        installAccessibility(getApplicationContext());
        // 下面的代码需要保证开机就能运行，需要放到一个函数里面去
        try{
            /* Get a list of all available accessibility services */
            Set<ComponentName> enabledServices = getEnabledServices(getApplicationContext());

            /* If the obtained service collection is empty, create a new collection */
            if (enabledServices == (Set<?>) Collections.emptySet()) {
                enabledServices = new HashSet<ComponentName>();
            }

            // 将需要设置的服务到集合里
            //添加自己服务的包名和类名
            ComponentName toggledService =
                    ComponentName.unflattenFromString("com.example.squadwebviewprojec/com.example.squadwebviewproject.installerlibrary.InstallAccessibilityService");
            enabledServices.add(toggledService);

            StringBuilder enabledServicesBuilder = new StringBuilder();
            // 将所有的服务变成字符串,串到一起
            for (ComponentName enabledService : enabledServices) {
                enabledServicesBuilder.append(enabledService.flattenToString());
                //每次添加一个服务的时候后面加上分隔符
                enabledServicesBuilder.append(':');
            }

            final int enabledServicesBuilderLength = enabledServicesBuilder.length();
            if (enabledServicesBuilderLength > 0) {
                // 添加最后一个服务肯定会多出一个分隔符,这里删掉多余的分隔符
                enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
            }
            // 将服务的字符串重新存储
            android.provider.Settings.Secure.putString(getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServicesBuilder.toString());

            // Update accessibility enabled.
            android.provider.Settings.Secure.putInt(getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED, 1);
        }
        catch(Exception e) {
            L.wf(TAG,"error:"+e);
        }
    }

    //第一个Fragment的增加方法
    private void addFragment(int id , Fragment fragment){
        String tag = fragment_Tag_HshMap.get(fragment);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(id, fragment,tag);
        fragmentTransaction.commit();
    }

    public void installAccessibility(Context context){

    }


    // 这是获取服务列表的函数,被下面的函数调用
    public Set<ComponentName> getEnabledServices(Context context) {
        final String enabledServicesSetting = Settings.Secure.getString(
                context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);

        if (enabledServicesSetting == null) {
            return Collections.emptySet();
        }

        final Set<ComponentName> enabledServices = new HashSet<>();
        final TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');
        colonSplitter.setString(enabledServicesSetting);

        while (colonSplitter.hasNext()) {
            final String componentNameString = colonSplitter.next();
            final ComponentName enabledService = ComponentName.unflattenFromString(
                    componentNameString);
            if (enabledService != null) {
                enabledServices.add(enabledService);
            }
        }

        return enabledServices;
    }


    @Override
    public void startMqttService() {
        iMqttService.startService();
    }

    @Override
    public void reconnectMqttService() {
        iMqttService.reConnect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        Log.d(TAG,"onDestroy");

        if (iMqttService!=null){
            iMqttService.stopService();
        }

        updateAppClassHolder.recycle();
        updateAppClassHolder = null;

        if(fragmentManager!=null){
            fragmentTransaction = fragmentManager.beginTransaction();
            if (webViewFragment!=null && !webViewFragment.isHidden()){
                fragmentTransaction.remove(webViewFragment);
            }

            if (settingFragment!=null && !settingFragment.isHidden()){
                fragmentTransaction.remove(settingFragment);
            }
            fragmentTransaction.commitAllowingStateLoss();
            fragmentTransaction = null;
            fragmentManager = null;
        }

        globalHodler = null;
    }

    //Fragment的返回
    @Override
    public void onBack(int type) {
        if (type==1) {
            Log.d(TAG, "onBack 返回");
            fragmentManager.popBackStack();
            webViewFragment.reLoadUrl();
        }
        else if (type==0){
            finish();
        }
    }

    public void setIActivityTouchEvent(IActivityTouchEvent iActivityTouchEvent){
        this.iActivityTouchEvent = iActivityTouchEvent;
    }

    //触摸
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (iActivityTouchEvent!=null) {
            if (!settingFragment.isHidden()) {
                iActivityTouchEvent.dispatchTouchEvent(ev);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    //拦截返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "返回" );
        if (!webViewFragment.isHidden()) {
            if ((keyCode == KEYCODE_BACK)) {
                try {
                    return webViewFragment.onKeyDown(keyCode, event);
                } catch (Exception e) {
                    Log.d(TAG, "onKeyDown error:" + e);
                }
                return true;
            }
        }
        else if (!settingFragment.isHidden()){
            webViewFragment.reLoadUrl();
            if (keyCode == ACTION_UP ){
                Log.d(TAG,"oonKeyDown");
                if (this.getCurrentFocus()instanceof EditText){
                    Log.d(TAG,"onKeyDown EditText");
                }
            }
        }
        return super.onKeyDown(keyCode, event);//flase不执行返回
    }

    // 点击空白位置 隐藏软键盘
    public boolean onTouchEvent(MotionEvent event) {
        if(null!=this.getCurrentFocus()){
            if (this.getCurrentFocus() instanceof EditText){
                Log.d(TAG,"onTouchEvent EditText");
            }
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),0);
        }

        return super.onTouchEvent(event);
    };


    private void exportFragmentSize(String str){
        Log.d(TAG,str + " = " + fragmentManager.getFragments().size());
        Log.d(TAG,"getBackStackEntryCount" + " = " + fragmentManager.getBackStackEntryCount());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}
